package com.itbaizhan.clouddemooauth2server.controller;


import com.itbaizhan.Constant;
import com.itbaizhan.clouddemooauth2server.dto.LoginDto;
import com.itbaizhan.clouddemooauth2server.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import java.net.URI;

@Controller
public class LoginController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 跳转到登录页面
     */
    @GetMapping("/toLogin")
    public  ModelAndView toLogin(){
        ModelAndView modelAndView = new ModelAndView("login");
        return modelAndView;
    }


    /**
     *  登录并请求令牌
     * @param loginDto
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody LoginDto loginDto){
        String client_id = Constant.client_id;   //客户端id
        String client_secret = Constant.client_secret; //客户端密码
        String grant_type_pwd = Constant.grant_type_pwd;  //请求令牌类型
        //请求令牌的url
        URI uri = URI.create(Constant.get_token_url
                + "?client_id=" + client_id + "&"
                + "client_secret=" + client_secret + "&"
                + "grant_type=" + grant_type_pwd + "&"
                + "username=" + loginDto.getUserName() + "&"
                + "password=" + loginDto.getPassword());

        Result result = restTemplate.getForObject(uri, Result.class);

        return result;
    }

}
